package webprog;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.fhwgt.quiz.application.Player;
import de.fhwgt.quiz.application.Quiz;
import de.fhwgt.quiz.error.QuizError;

@WebServlet("/Login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private Quiz quiz;
	private QuizError error;
	private Player spieler;
	private Verbindungsliste ver;
	 
	public void init(ServletConfig config) throws ServletException 
	{
		quiz = Quiz.getInstance();
		error = new QuizError();
		ver = Verbindungsliste.getInstance();
		
	}												
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{	
		response.setContentType("text/event-stream");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		String playerName = request.getParameter("name");
		

		System.out.println("Aufgerufen von: "+playerName);
		
		Collection <Player> players = quiz.getPlayerList();
		
		if(!playerName.isEmpty())
		{
			spieler = quiz.createPlayer(playerName, error);

			if(error.isSet())
			{
				System.out.println("#####Error: " + error.getStatus());
				
				writer.write("event: Error\n");
				writer.write("data: "+error.getDescription()+"\n\n");
				writer.flush();
				response.flushBuffer();
				error.set(null);
				ver.nameTaken();
			}else
			{
				System.out.println("Player " + playerName+ " hinzugefuegt");
				
				for(Player p : players){
					System.out.println("Player: " + p.getName() + "  " + p.getId());
				}
			
				quiz.signalPlayerChange();
				if(spieler.isSuperuser())
				{
					System.out.println("Spielleiter setzen");
					writer.write("event: SpielleiterSetzen\n");
					writer.write("data: 0\n\n");
					writer.flush();
					response.flushBuffer();
				}
				
				for(Player elem: players)
				{
					writer.write("event: PlayerChange\n");  
					writer.write("data: " + elem.getName() + "\n");
					writer.write("data: " + elem.getScore() + "\n"); 
					writer.write("data: " + elem.getId() + "\n");
				}
				writer.write("data: 0\n\n");
				writer.flush();
				
				new HighscoreAktualiesieren(response);
			}
		}else
		{
			writer.write("event: Error\n");
			writer.write("data: Bitte ein Namen eingeben!\n\n");
			writer.flush();
			response.flushBuffer();
		}
		
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

}
